iT邦幫忙

2023 iThome 鐵人賽

DAY 22
0
Mobile Development

App從開發到上架系列 第 22

Day24: iOS 開發:畫面功能(查找附近餐廳)

  • 分享至 

  • xImage
  •  
import UIKit
import CoreLocation

class RestaurantSearchViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var tableView: UITableView!
    
    let locationManager = CLLocationManager()
    var restaurants: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        
        tableView.dataSource = self
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let userLocation = locations.first else {
            return
        }
        
        let latitude = userLocation.coordinate.latitude
        let longitude = userLocation.coordinate.longitude

        let apiUrl = "https://api.example.com/restaurants?lat=\(latitude)&lon=\(longitude)"
        guard let url = URL(string: apiUrl) else { return }
        
        URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("Error: \(error)")
            } else if let data = data {

                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
                    if let restaurantsArray = json?["restaurants"] as? [String] {
                        self.restaurants = restaurantsArray
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                    }
                } catch {
                    print("JSON parsing error: \(error)")
                }
            }
        }.resume()
    }
}

extension RestaurantSearchViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return restaurants.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantCell", for: indexPath)
        cell.textLabel?.text = restaurants[indexPath.row]
        return cell
    }
}


上一篇
Day23: iOS 開發:我的第一支API!
下一篇
Day25: iOS 開發:簡單的餐廳訂位功能 - 試著把前後端給串接起來!
系列文
App從開發到上架30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言